
import api from './api.js';
import { checkLoginStatus, showMessage, formatPrice } from './common.js';
import UserManager from './tokenManager.js';

const { shoppingCart, orders } = api;
// 加载购物车
async function loadCart() {
    const user = await checkLoginStatus();
    if (!user) {
        showMessage('warning', '请先登录');
        window.location.href = 'login.html';
        return;
    }

    try {
        const response = await shoppingCart.getByUser(user.id);
        if (response.success) {
            renderCartItems(response.data);
            updateSummary(response.data);
        } else {
            showEmptyCart();
        }
    } catch (error) {
        showMessage('error', '加载购物车失败');
        showEmptyCart();
    }
}

// 渲染购物车商品
function renderCartItems(cartItems) {
    const cartItemsContainer = document.getElementById('cart-items');
    if (!cartItemsContainer) return;

    cartItemsContainer.innerHTML = '';

    if (!cartItems || cartItems.length === 0) {
        showEmptyCart();
        return;
    }

    cartItems.forEach(item => {
        const cartItem = document.createElement('div');
        cartItem.className = 'cart-item';
        cartItem.innerHTML = `
            <div class="item-image">
                <img src="/uploads/products/${item.product.images?.[0] || 'default-product.jpg'}" alt="${item.product.name}">
            </div>
            <div class="item-info">
                <h3><a href="product-detail.html?id=${item.product.id}">${item.product.name}</a></h3>
                <div class="price">${formatPrice(item.product.price)}</div>
                <div class="seller">卖家: ${item.product.seller?.username || '未知'}</div>
            </div>
            <div class="item-quantity">
                <button class="quantity-btn decrease" data-id="${item.id}">-</button>
                <input type="number" class="quantity-input" value="${item.quantity}" min="1" max="${item.product.stock}" data-id="${item.id}">
                <button class="quantity-btn increase" data-id="${item.id}">+</button>
            </div>
            <div class="item-subtotal">${formatPrice(item.product.price * item.quantity)}</div>
            <div class="item-actions">
                <button class="btn btn-remove" data-id="${item.id}">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;
        cartItemsContainer.appendChild(cartItem);
    });

    // 添加事件监听
    document.querySelectorAll('.quantity-btn.decrease').forEach(btn => {
        btn.addEventListener('click', updateCartItemQuantity);
    });

    document.querySelectorAll('.quantity-btn.increase').forEach(btn => {
        btn.addEventListener('click', updateCartItemQuantity);
    });

    document.querySelectorAll('.quantity-input').forEach(input => {
        input.addEventListener('change', updateCartItemQuantity);
    });

    document.querySelectorAll('.btn-remove').forEach(btn => {
        btn.addEventListener('click', removeCartItem);
    });
}

// 更新购物车项数量
async function updateCartItemQuantity(e) {
    const cartItemId = e.target.dataset.id;
    const quantityInput = document.querySelector(`.quantity-input[data-id="${cartItemId}"]`);
    let quantity = parseInt(quantityInput.value);

    if (e.target.classList.contains('decrease')) {
        if (quantity > 1) quantity--;
    } else if (e.target.classList.contains('increase')) {
        quantity++;
    } else {
        // 直接输入的情况
        quantity = parseInt(e.target.value) || 1;
    }

    try {
        const response = await shoppingCart.update({
            id: cartItemId,
            quantity
        });

        if (response.success) {
            quantityInput.value = quantity;
            loadCart(); // 重新加载购物车更新总计
        }
    } catch (error) {
        showMessage('error', '更新数量失败');
    }
}

// 移除购物车项
async function removeCartItem(e) {
    const cartItemId = e.target.closest('button').dataset.id;

    try {
        const response = await shoppingCart.remove(cartItemId);
        if (response.success) {
            showMessage('success', '已移除商品');
            loadCart();
        }
    } catch (error) {
        showMessage('error', '移除商品失败');
    }
}

// 更新订单摘要
function updateSummary(cartItems) {
    const totalItems = cartItems.reduce((sum, item) => sum + item.quantity, 0);
    const subtotal = cartItems.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);
    const shippingFee = subtotal > 100 ? 0 : 10; // 假设满100免运费
    const totalPrice = subtotal + shippingFee;

    document.getElementById('total-items').textContent = totalItems;
    document.getElementById('subtotal').textContent = formatPrice(subtotal);
    document.getElementById('shipping-fee').textContent = formatPrice(shippingFee);
    document.getElementById('total-price').textContent = formatPrice(totalPrice);
}

// 显示空购物车
function showEmptyCart() {
    const cartItemsContainer = document.getElementById('cart-items');
    if (!cartItemsContainer) return;

    cartItemsContainer.innerHTML = `
        <div class="empty-cart">
            <img src="images/empty-cart.png" alt="空购物车">
            <p>您的购物车是空的</p>
            <a href="products.html" class="btn btn-primary">去逛逛</a>
        </div>
    `;

    // 重置摘要
    document.getElementById('total-items').textContent = '0';
    document.getElementById('subtotal').textContent = formatPrice(0);
    document.getElementById('shipping-fee').textContent = formatPrice(0);
    document.getElementById('total-price').textContent = formatPrice(0);
}

// 结算功能
document.getElementById('checkout-btn')?.addEventListener('click', async function() {
    const user = await checkLoginStatus();
    if (!user) {
        showMessage('warning', '请先登录');
        window.location.href = 'login.html';
        return;
    }

    try {
        const cartResponse = await shoppingCart.getByUser(user.id);
        if (!cartResponse.success || cartResponse.data.length === 0) {
            showMessage('warning', '购物车为空');
            return;
        }

        const cartItems = cartResponse.data;
        const orderData = {
            userId: user.id,
            items: cartItems.map(item => ({
                productId: item.product.id,
                quantity: item.quantity
            })),
            totalAmount: cartItems.reduce((sum, item) => sum + (item.product.price * item.quantity), 0)
        };

        const orderResponse = await orders.create(orderData);
        if (orderResponse.success) {
            // 清空购物车
            await shoppingCart.batchRemove(cartItems.map(item => item.id));
            window.location.href = `order-detail.html?id=${orderResponse.data.id}`;
        }
    } catch (error) {
        showMessage('error', '结算失败');
    }
});

// 页面加载时执行
document.addEventListener('DOMContentLoaded', loadCart);